package ch.zbw.sysventory.server.scanner;

import org.apache.log4j.Logger;

import ch.zbw.sysventory.server.model.ComputerScan;
import ch.zbw.sysventory.server.model.ScanConfiguration;

public class NetworkScanJob extends Thread implements Runnable {

	private Logger logger = Logger.getRootLogger();

	private ScanManager scanManager;
	private ScanConfiguration scanConfiguration;
	private ConnectionTester connectionTester;
	private boolean finished = false;
	private ComputerScanner computerScanner;
	private ComputerScan computerScan;

	public NetworkScanJob(ScanManager scanManager, ScanConfiguration scanConfiguration, ComputerScanner computerScanner, ComputerScan computerScan) {
		this.scanManager = scanManager;
		this.scanConfiguration = scanConfiguration;
		this.computerScanner = computerScanner;
		this.computerScan = computerScan;
	}

	@Override
	public void run() {
		this.connectionTester = new ConnectionTester();
		IPManager ipManager = new IPManager(this.scanConfiguration.getStartIp(), this.scanConfiguration.getEndIp());
		while (ipManager.hasMoreElements()) {
			String nextIp = ipManager.nextElement();
			this.log("Try to connect to ip: " + nextIp);
			if (this.connectionTester.testConnection(nextIp, this.scanConfiguration.getAgentPort())) {
				this.log("Found computer under ip: " + nextIp);
				try {
					this.computerScanner.scanComputer(nextIp, this.scanConfiguration.getAgentPort(), this.computerScan);
				} catch (Exception e) {
					this.log("Scan of computer '" + nextIp + "' failed: " + e.getMessage());
				}
			}
		}
		this.finished = true;
		this.scanManager.setScanJobFinished();
	}

	public boolean isFinished() {
		return finished;
	}

	private void log(String message) {
		logger.info(message);
		this.scanManager.log(message);
	}

}
